var cookie = require("./cookie");
var async = require("async");
var langLoader = require("./langLoader");
var apiLoader = require("./apiLoader");
var fs = require("fs");
var ejs = require("ejs");
var stream = require('stream');
var Tools = require('./tools');
var renderEngin = function(pageName, Com, storage) {
    var userType = cookie.get(this.req, "userType");
    var primary = cookie.get(this.req, "primary");
    var view = {};
    var res = this;
    var language = cookie.getCurrentLanguage(this);
    function getLangData(done) {
        langLoader(pageName, language, function(langData) {
            done(null, langData);
        });
    }
    function getApi(done) {
        apiLoader(pageName, function(apiData) {
            done(null, apiData);
        });
    }
    function getSeo(done) {
        Tools.getSeoData(pageName, function(seoData) {
            done(null, seoData);
        });
    }
    fs.readFile("views/" + pageName + ".html", function(error, data) {
        pageContent = data.toString();
        async.parallel({
            langData: getLangData,
            apiData: getApi,
            seoData: getSeo
        }, function(err, result) {
            if(storage) {
                if(storage["slider"]) {
                    storage["slider"]["activeItem"] = res.req.url;
                    storage["slider"]["userType"] = userType;
                    storage["slider"]["primary"] = primary;
                }
                delete result.apiData.host;
                delete result.apiData.port;
                delete result.apiData.fileHost;
                delete result.apiData.filePort;
                storage["lang"] = result.langData;
                view["storage"] = "<script>window.Interface=" + JSON.stringify(result.apiData) + "</script><script>window.storage=" + JSON.stringify(storage) + "</script>";
            }
            view["view"] = ReactDOMServer.renderToString(Com({data: storage}));
            var buffer = ejs.render(pageContent, {view:view["view"], seo:result.seoData, storage:view["storage"], filename:"views/header.html"});
            var bufferStream = new stream.PassThrough();
            bufferStream.end(buffer);
            res.write('<head><meta charset="utf-8"/></head>');
            bufferStream.on('data', function(chunk) {
                if(!res.write(chunk)){//判断写缓冲区是否写满(node的官方文档有对write方法返回值的说明)
                    bufferStream.pause();//如果写缓冲区不可用，暂停读取数据
                }
            });
            bufferStream.on('end', function () {
                res.end();
            });
            res.on("drain", function () {//写缓冲区可用，会触发"drain"事件
                bufferStream.resume();//重新启动读取数据
            });
        });
    });
}
module.exports = renderEngin;